import random
from datetime import datetime
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.modules.passport import passport_blu
from flask import request,abort,current_app,make_response,jsonify,session
from info import redis_store, constants, db
from info.utils.captcha.captcha import captcha
import json
import re
from info.utils.response_code import RET
# from werkzeug.security import generate_password_hash



@passport_blu.route("/logout")
def logout():
    session.pop('user_id', None)
    # session.pop('mobile', None)
    # session.pop('nick_name', None)

    return jsonify(errno=RET.OK, errmsg="退出成功")




@passport_blu.route("/login",methods = ["POST"])
def login():
    dict_data = request.json
    mobile = dict_data.get("mobile")
    passport = dict_data.get("passport")

    if not all([mobile,passport]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if not re.match(r"1[35678]\d{9}",mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号格式不正确")

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询错误")


    if not user:
        return jsonify(errno=RET.NODATA,errmsg="没有用户注册")

    if not user.check_passowrd(passport):
        return jsonify(errno=RET.DATAERR,errmsg="密码输入错误")

    user.last_login = datetime.now()


    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    session["user_id"] = user.id

    return jsonify(errno=RET.OK, errmsg="登录成功")



@passport_blu.route("/register",methods=["POST"])
def register():
    dict_data = request.json
    mobile = dict_data.get("mobile")
    smscode = dict_data.get("smscode")
    password = dict_data.get("password")

    if not all([mobile,smscode,password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")


    # 正则验证
    if not re.match(r"1[35678]\d{9}",mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号格式不正确")



    try:
        real_sms_code = redis_store.get("SMS_" + mobile)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询失败")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA,errmsg="验证码已经过期")

    if real_sms_code != smscode:
        return jsonify(errno=RET.DATAERR,errmsg="验证码错误")

    user = User()
    user.nick_name = mobile
    # user.password_hash = generate_password_hash(password)
    user.password = password
    user.mobile = mobile

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    # session 保持用户登录状态
    session["user_id"] = user.id
    return jsonify(errno=RET.OK, errmsg="注册成功")




@passport_blu.route("/sms_code",methods = ["POST"])
def get_sms_code():
    """
    1.接收参数 mobile，image_code,image_code_id
    2.校验参数：mobile正则
    3.校验用户输入验证码和通过image_code_id查询出来的验证码是否一致
    4.定义一个6位数的验证码
    5.调用云通信发送手机验证码
    6.将验证码保存到redis中
    7.给前端一个响应
    :return:
    """
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json

    # 接收参数
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 全局验证
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")


    # 正则验证
    if not re.match(r"1[35678]\d{9}",mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号格式不正确")

    try:
        real_image_code = redis_store.get("ImageCodeId_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="数据库查询失败")
    if not real_image_code:
        return jsonify(errno=RET.DATAERR,errmsg="图片验证码已经过期")

    if image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码输入错误")

#     定义一个六位数的验证码
    # "%06d" 将一个数字转化为6位数字，如果位数不够，用0填充   1234   001234
    sms_code_str = "%06d" % random.randint(0,999999)
    current_app.logger.error("短信验证码为%s" % sms_code_str)

    result = CCP().send_template_sms(mobile,[sms_code_str,constants.SMS_CODE_REDIS_EXPIRES/60],1)
    if result != 0:
        return jsonify(errno=RET.THIRDERR,errmsg="短信验证码发送失败")

    # 将验证码保存到redis中
    try:
        redis_store.setex("SMS_" + mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code_str)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="手机验证码保存失败")

    # 7、给前端一个响应
    return jsonify(errno=RET.OK, errmsg="成功发送短信验证码")



@passport_blu.route("/image_code")
def get_image_code():
    image_code_id = request.args.get("imageCodeId")

    if not image_code_id:
        abort(404)

    _,text,image = captcha.generate_captcha()
    current_app.logger.info("图片验证码为%s" % text)
    try:
        redis_store.setex("ImageCodeId_" + image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"

    return response